package com.zb.emq;

import com.zb.config.EmqConfig;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.UUID;

@Component
@Slf4j
public class EmqClient {
    @Autowired
    private EmqConfig emqConfig;

    //emq中连接mqtt服务器的客户端对象
    private MqttClient mqttClient;

    @Autowired
    private EmqMsgProcess msgProcess;

    /**
     * 连接服务器
     */
    public void connect() {
        log.info("创建emqx服务器连接");
        try {
            mqttClient = new MqttClient(emqConfig.getMqttServerUrl(), "monitor." + UUID.randomUUID().toString());
            mqttClient.connect();
            //添加回调，生成发送数据到当前的程序 主动接收消息（回调）
            mqttClient.setCallback(msgProcess);
        } catch (MqttException e) {
            e.printStackTrace();
            log.error("创建连接失败！");
        }
    }

    /**
     * 消息发送
     *
     * @param topic
     * @param msg
     */
    public void publish(String topic, String msg) {
        log.info("发送的主题:" + topic + "，发送的内容是：" + msg);
        MqttMessage mqttMessage = new MqttMessage(msg.getBytes());
        try {
            //将消息发送到指定的主题上
            mqttClient.getTopic(topic).publish(mqttMessage);
        } catch (MqttException e) {
            e.printStackTrace();
            log.error("发送消息失败！");
        }
    }

    /**
     * 订阅主题
     *
     * @param topicName
     * @throws Exception
     */
    public void subscribe(String topicName) throws Exception {
        mqttClient.subscribe(topicName);
    }


}
